<template>
  <div>
    <upload-excel :onSuccess="onSuccess" />
  </div>
</template>

<script setup>
import { userBatchImport } from '@/api/user-manage'
import UploadExcel from '@/components/UploadExcel'
import { formatDate } from './utils'
import { ElMessage } from 'element-plus'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'
const i18n = useI18n()
const router = useRouter()
const onSuccess = async ({ header, results }) => {
  const updateData = processData(results)
  await userBatchImport(updateData)
  ElMessage.success({
    message: updateData.length + i18n.t('msg.excel.importSuccess')
  })
  router.push('/user/manage')
}
// 映射传递的数据
const userRelations = {
  姓名: 'username',
  联系方式: 'mobile',
  角色: 'role',
  开通时间: 'openTime'
}
const processData = (results) => {
  const res = []
  results.forEach((item) => {
    const userInfo = {}
    Object.keys(item).forEach((key) => {
      if (userRelations[key] === 'openTime') {
        userInfo[userRelations[key]] = formatDate(item[key])
        return
      }
      userInfo[userRelations[key]] = item[key]
    })
    res.push(userInfo)
  })
  console.log('res', res)
  return res
}
</script>

<style lang="scss" scoped></style>
